package com.orm.mybatis.token.controller;

import com.alibaba.fastjson.JSONObject;
import com.orm.mybatis.token.annotation.PassToken;
import com.orm.mybatis.token.entity.User;
import com.orm.mybatis.token.mapper.UserMapper1;
import com.orm.mybatis.token.serviceImpl.UserServiceImpl;
import com.orm.mybatis.token.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
public class TestLoginController {

    /**
     * 用户登录的接口,校验数据库之后,调用token工具类生成token返回客户端
     *
     * @param user  用户信息
     * @return 返回的信息
     */
    @Resource
    private UserMapper1 userMapper1;

    @PostMapping(value = "/login",produces = {"application/json;charset=UTF-8"})
    public HashMap<String,Object> login(@RequestBody String json){
        JSONObject jsonObject = JSONObject.parseObject(json);
        String name = jsonObject.getString("name");
        String password = jsonObject.getString("password");
        HashMap<String,String> claim = new HashMap<>();
        claim.put("name",name);
        User user = userMapper1.selectUserByName(name);
        HashMap<String,Object> hashMap = new HashMap<>();
        if (null == user ){
            hashMap.put("rv",400);
            hashMap.put("message","登录失败,用户不存在");
            return hashMap;
        }else{
            //用户校验成功
            String token = TokenUtil.createToken(claim);
            hashMap.put("token",token);
            hashMap.put("rv",200);
            hashMap.put("message", "认证成功");
        }
        return hashMap;
    }

    @GetMapping("/test/one")
    public HashMap<String,String> test1(HttpServletRequest httpServletRequest){
      String token = httpServletRequest.getHeader("token");
      String name = TokenUtil.decodeToken(token).getClaim("name").asString();
      String subject = TokenUtil.decodeToken(token).getSubject();
      HashMap<String,String> hashMap = new HashMap<>();
      hashMap.put("one","one");
      hashMap.put("name",name);
      hashMap.put("subject",subject);
      return hashMap;
    }

    @PassToken
    @GetMapping("/test/two")
    public HashMap<String,String> test2(User user){
        System.out.println(user.toString());
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("two","two");
        return hashMap;
    }

    @PassToken(value = false)
    @GetMapping("/test/three")
    public HashMap<String,String> test3(){
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("three","three");
        return hashMap;
    }
}
